package 算法.leetcode.labuladong.数组和链表;

import java.util.ArrayList;

/**
 * https://leetcode.cn/problems/product-of-the-last-k-numbers/
 *
 * @author lchenglong
 * @date 2022/6/15
 */
public class 最后K个数的乘积 {

    public static void main(String[] args) {
        ProductOfNumbers ins = new ProductOfNumbers();
        ins.add(3);
        ins.add(0);
        ins.add(2);
        ins.add(5);
        ins.add(4);
        System.out.println(ins.getProduct(4));
    }
    static class ProductOfNumbers {
        ArrayList<Integer> preProducts;

        public ProductOfNumbers() {
            preProducts = new ArrayList<>();
            // 初始化放一个 1，便于计算后续添加元素的乘积
            preProducts.add(1);
        }

        public void add(int num) {
            if (num == 0){
                preProducts.clear();
                // 以备后面使用
                preProducts.add(1);
            } else {
                preProducts.add(preProducts.get(preProducts.size()-1) * num);
            }
        }

        public int getProduct(int k) {
            int n = preProducts.size();
            if (k> n-1){
                // 不足K个数,前面肯定有0
                return 0;
            } else {
                // 计算最后K个元素乘积
                return preProducts.get(n-1)/preProducts.get(n-k-1);
            }
        }


    }
}
